package com.yh.modules.data.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.common.constant.CheckEnums;
import com.yh.common.constant.CheckTypeEnums;
import com.yh.common.constant.Constant;
import com.yh.common.exception.RRException;
import com.yh.common.utils.Assert;
import com.yh.common.utils.JacksonUtils;
import com.yh.common.utils.PageUtils;
import com.yh.common.utils.Query;
import com.yh.modules.data.dao.MachineDataDao;
import com.yh.modules.data.entity.*;
import com.yh.modules.data.service.*;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service("machineDataService")
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class MachineDataServiceImpl extends ServiceImpl<MachineDataDao, MachineDataEntity> implements MachineDataService {

    @Autowired
    private DataMsgService dataMsgService;

    @Autowired
    private MachineService machineService;

    @Autowired
    private ErrorTypeService errorTypeService;

    @Autowired
    private OkTypeService okTypeService;


    @Autowired
    private MachineCheckService machineCheckService;


    @Autowired
    private MachineDataDao machineDataDao;

    @Override
    public PageUtils getMachineDataList(Map<String, Object> params) {
        Integer machineId = MapUtil.getInt(params, "machineId");
        Integer status = MapUtil.getInt(params, "status");
        String startTime = MapUtil.getStr(params, "startTime");
        String endTime = MapUtil.getStr(params, "endTime");
        Assert.isNull(machineId, "机器id不能为空");

        EntityWrapper<MachineDataEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("machine_id", machineId);
        wrapper.eq(ObjectUtil.isNotNull(status), "status", status);
        wrapper.ge(StrUtil.isNotBlank(startTime), "start_time", startTime);
        wrapper.le(StrUtil.isNotBlank(endTime), "end_time", endTime);

        Page<MachineDataEntity> page = this.selectPage(new Query<MachineDataEntity>(params).getPage(), wrapper);

        ConvertMachineDataEntity convertMachineDataEntity = getConvertMachineDataEntity(machineId);
        List<Map<String, Object>> resultList = convertMachineDataList(page.getRecords(), convertMachineDataEntity);

        return new PageUtils(resultList, page);
    }

    private ConvertMachineDataEntity getConvertMachineDataEntity(Integer machineId) {
        return ConvertMachineDataEntity.builder()
                .colModelList(getColNamesAndModel(machineId).getColModelList())
                .errorTypeMap(getErrorTypeMap(machineId))
                .build();
    }

    private Map<Integer, String> getErrorTypeMap(Integer machineId) {
        List<ErrorTypeEntity> errorTypeList = errorTypeService.getErrorTypeListByMachineId(machineId);
        Map<Integer, String> errorTypeMap = new HashMap<>();
        for (ErrorTypeEntity typeEntity : errorTypeList) {
            errorTypeMap.put(typeEntity.getId(), typeEntity.getDescription());
        }
        log.debug("获取错误类型map:{}", errorTypeMap);
        return errorTypeMap;
    }


    @Override
    public Map<String, Object> getMachineDataAnalyze(Map<String, Object> params) {
        Integer machineId = MapUtil.getInt(params, "machineId");
        Assert.isNull(machineId, "机器id不能为空");

        List<DataAnalyzeEntity> dataAnalyzeList = baseMapper.getMachineDataAnalyze(params);
        log.debug("数据分析dataAnalyzeList:{}" + dataAnalyzeList);

        JqGridEntity jqGridEntity = getAnalyzeColNamesAndModel(machineId);
        List<String> colModelList = jqGridEntity.getColModelList();
        List<String> errorTypeNameList = jqGridEntity.getErrorTypeNameList();
        Map<String, Object> colModel = new HashMap<>();
        //计算总数
        Integer totalCount = getTotalCount(dataAnalyzeList);
        colModel.put("totalCount", totalCount);
        //计算合格数
        Integer qualifiedCount = getQualifiedCount(dataAnalyzeList);
        colModel.put("qualifiedCount", qualifiedCount);
        //计算不合格数
        colModel.put("disqualifiedCount", getDisqualifiedCount(dataAnalyzeList));
        //计算合格率
        colModel.put("qualificationRate", calculateQualificationRate(qualifiedCount, totalCount));
        //查询每个错误类型对应的数量
        for (String key : colModelList) {
            if (key.startsWith("errorType")) {
                colModel.put(key, getErrorCount(key, dataAnalyzeList));
            }
        }
        colModel.put("errorTypeNameList", errorTypeNameList);
        if (CollUtil.isEmpty(dataAnalyzeList)) {
            colModel.put("chartsDataList", getChartsDataListWithNoError(errorTypeNameList));
        } else {
            colModel.put("chartsDataList", getChartsDataList(dataAnalyzeList));
        }
        return colModel;
    }

    private List<Map<String, Object>> getChartsDataListWithNoError(List<String> typeNameList) {
        List<Map<String, Object>> chartsDataList = new ArrayList<>();
        for (String typeName : typeNameList) {
            Map<String, Object> chartsDataMap = new HashMap<>();
            chartsDataMap.put("value", 0);
            chartsDataMap.put("name", typeName);
            chartsDataList.add(chartsDataMap);
        }
        return chartsDataList;
    }

    private List<Map<String, Object>> getChartsDataList(List<DataAnalyzeEntity> dataAnalyzeList) {

        List<Map<String, Object>> chartsDataList = new ArrayList<>();
        for (DataAnalyzeEntity dataAnalyzeEntity : dataAnalyzeList) {
            if (dataAnalyzeEntity.getErrorType() != Constant.ERROR_TYPE_SUCCESS) {
                Map<String, Object> chartsDataMap = new HashMap<>();
                chartsDataMap.put("value", dataAnalyzeEntity.getCount());
                chartsDataMap.put("name", dataAnalyzeEntity.getErrorDesc());
                chartsDataList.add(chartsDataMap);
            }
        }
        return chartsDataList;
    }

    private List<Map<String, Object>> getOkTypeChartsDataList(List<DataStatisticsEntity> dataStatisticsList) {

        List<Map<String, Object>> chartsDataList = new ArrayList<>();
        for (DataStatisticsEntity dataStatisticsEntity : dataStatisticsList) {
            if (dataStatisticsEntity.getOkType() != Constant.OK_TYPE_SUCCESS) {
                Map<String, Object> chartsDataMap = new HashMap<>();
                chartsDataMap.put("value", dataStatisticsEntity.getCount());
                chartsDataMap.put("name", dataStatisticsEntity.getOkDesc());
                chartsDataList.add(chartsDataMap);
            }
        }
        return chartsDataList;
    }

    @Override
    public List<Map<String, Object>> getMachineDataCheck(Map<String, Object> params) {
        Integer machineId = MapUtil.getInt(params, "machineId");
        String time = MapUtil.getStr(params, "time");
        Integer machineCheckId = MapUtil.getInt(params, "machineCheckId");
        Assert.isNull(machineId, "机器id不能为空");
        Assert.isNull(machineCheckId, "机器检测配置信息Id不能为空");
        Assert.isBlank(time, "时间不能为空");

        //获取机器的检测配置信息
        MachineCheckEntity machineCheck = machineCheckService.selectById(machineCheckId);
        if (machineCheck == null) {
            throw new RRException("机器配置信息不存在,请管理员填写配置信息,id:" + machineCheckId);
        }

        //转换时间格式
        String startTime = DateUtil.parseDateTime(time + " " + machineCheck.getStartTime()).toString();
        String endTime = DateUtil.parseDateTime(time + " " + machineCheck.getEndTime()).toString();

        //校验时间:当前时间必须比结束时间要晚,否则返回空数据.
        Boolean timeValid = checkTimeValid(endTime);
        if (!timeValid) {
            throw new RRException("当前时间段无效,无法获取数据");
        }

        //获取已经抽检的数据
        List<MachineDataEntity> checkedMachineDataList = getMachineCheckData(machineId, startTime, endTime, CheckEnums.CHECKED.getCode());
        log.debug("时间范围:{} - {} , 已经抽检的数据:{}", startTime, endTime, JacksonUtils.obj2json(checkedMachineDataList));

        ConvertMachineDataEntity convertMachineDataEntity = getConvertMachineDataEntity(machineId);

        if (CollUtil.isNotEmpty(checkedMachineDataList)) {
            log.debug("已经抽检的数据不为空,直接返回");
            return convertMachineDataList(checkedMachineDataList, convertMachineDataEntity);
        } else {
            //抽检数据为空,说明以前没有抽检过,开始抽检,先获取未抽检过的数据
            List<MachineDataEntity> uncheckMachineDataList = getMachineCheckData(machineId, startTime, endTime, CheckEnums.UNCHECKED.getCode());
            if (CollUtil.isEmpty(uncheckMachineDataList)) {
                //未抽检过的数据为空
                throw new RRException("该时间段没有数据");
            } else {
                log.debug("时间范围:{} - {} , 未抽检的数据的大小:{}", startTime, endTime, uncheckMachineDataList.size());
                return getCheckDataList(machineCheck, uncheckMachineDataList, convertMachineDataEntity);
            }
        }
    }

    @Override
    public JqGridEntity getColNamesAndModel(@NonNull Integer machineId) {
        List<DataMsgEntity> dataMsgList = dataMsgService.getDataMsgListByMachineId(machineId);

        if (CollUtil.isEmpty(dataMsgList)) {
            throw new RRException("请管理员填写检测数据的配置信息");
        }

        List<String> colNameList = dataMsgList.stream().map(DataMsgEntity::getParamInfo).collect(Collectors.toList());
        log.debug("表头列表:{}", colNameList);
        List<String> colModelList = dataMsgList.stream().map(DataMsgEntity::getParamName).collect(Collectors.toList());
        log.debug("模型列表:{}", colModelList);
        List<Integer> sortList = dataMsgList.stream().map(DataMsgEntity::getSort).collect(Collectors.toList());

        //根据colModelList拼装colModel
        //{ label: '项目id', name: 'id', index: 'id', width: 50,sortable: false, key: true },
        List<Map<String, Object>> colModelEntity = assembleJqidColModelList(colNameList, colModelList);
        log.debug("colModel实体:{}", colModelEntity);

        JqGridEntity jqGridEntity = new JqGridEntity();
        jqGridEntity.setColNameList(colNameList);
        jqGridEntity.setColModelList(colModelList);
        jqGridEntity.setSortList(sortList);
        jqGridEntity.setColModelEntity(colModelEntity);
        jqGridEntity.setMachineEntity(machineService.selectById(machineId));

        return jqGridEntity;
    }


    @Override
    public JqGridEntity getAnalyzeColNamesAndModel(@NonNull Integer machineId) {
        //从errry_type表中查询数据
        List<ErrorTypeEntity> errorTypeList = errorTypeService.getErrorTypeListByMachineId(machineId);

        List<String> colNameList = CollUtil.newArrayList("总数", "合格数", "不合格数", "合格率");
        List<String> errorTypeNameList = errorTypeList.stream().map(ErrorTypeEntity::getDescription).collect(Collectors.toList());
        colNameList.addAll(errorTypeNameList);
        log.debug("表头列表:{}", colNameList);

        List<String> colModelList = CollUtil.newArrayList("totalCount", "qualifiedCount", "disqualifiedCount", "qualificationRate");
        List<String> errorTypeModelList = errorTypeList.stream().map(errorTypeEntity -> "errorType" + errorTypeEntity.getId()).collect(Collectors.toList());
        colModelList.addAll(errorTypeModelList);
        log.debug("模型列表:{}", colModelList);

        List<Integer> sortList = errorTypeList.stream().map(ErrorTypeEntity::getSort).collect(Collectors.toList());

        //根据colModelList拼装colModel
        //{ label: '项目id', name: 'id', index: 'id', width: 50,sortable: false, key: true },
        List<Map<String, Object>> colModelEntity = assembleJqidColModelList(colNameList, colModelList);
        log.debug("colModel实体:{}", colModelEntity);

        MachineEntity machineEntity = machineService.selectById(machineId);
        JqGridEntity jqGridEntity = new JqGridEntity();
        jqGridEntity.setColNameList(colNameList);
        jqGridEntity.setColModelList(colModelList);
        jqGridEntity.setSortList(sortList);
        jqGridEntity.setColModelEntity(colModelEntity);
        jqGridEntity.setMachineEntity(machineEntity);
        jqGridEntity.setErrorTypeNameList(errorTypeNameList);

        return jqGridEntity;
    }

    @Override
    public void deleteDataFromAWeekAge() {
        Integer rows = baseMapper.deleteDataFromAWeekAge();
        log.info("[删除一周前数据],成功删除{}条记录", rows);
    }

    @Override
    public void getMachineWorkCount(MachineDataWorkCountQueryForm form) {
        List<MachineCountResult> machineCountResultList = machineDataDao.getMachineWorkCount(form.getMachineId(), form.getTime());
        Map<String, Integer> time = getTime();
        for (MachineCountResult machineCountResult : machineCountResultList) {
            if (time.containsKey(machineCountResult.getTime())) {
                time.put(machineCountResult.getTime(), machineCountResult.getCount());
            }
        }
        for (String key : time.keySet()) {
            log.info("key:{},value:{}", key, time.get(key));
        }
    }

    @Override
    public Map<String, Object> getMachineDataStatistics(Map<String, Object> params) {

        Integer machineId = MapUtil.getInt(params, "machineId");
        Assert.isNull(machineId, "机器id不能为空");

        JqGridEntity jqGridEntity = getStatisticsColNamesAndModel(machineId);

        List<DataStatisticsEntity> dataStatisticsList = baseMapper.getMachineDataStatistics(params);
        log.debug("数据统计dataStatisticsList:{}",dataStatisticsList);

        List<String> colModelList = jqGridEntity.getColModelList();
        List<String> okTypeNameList =jqGridEntity.getOkTypeNameList();
        Map<String, Object> colModel = new HashMap<>();
        //查询每个ok类型对应的数量
        for (String key : colModelList) {
            if (key.startsWith("okType")) {
                colModel.put(key, getOkCount(key, dataStatisticsList));
            }
        }
        colModel.put("okTypeNameList", okTypeNameList);
        if (CollUtil.isEmpty(dataStatisticsList)) {
            colModel.put("chartsDataList", getChartsDataListWithNoError(okTypeNameList));
        } else {
            colModel.put("chartsDataList", getOkTypeChartsDataList(dataStatisticsList));
        }

        //拼接图表数据
        List<Integer> valueList = getDataStatisticsValueList(colModel);
        colModel.put("valueList", valueList);
        return colModel;
    }

    private List<Integer> getDataStatisticsValueList(Map<String, Object> colModel) {
        List<Map<String, Object>> chartsDataList = (List<Map<String, Object>>) colModel.get("chartsDataList");
        List<Integer> valueList = new ArrayList<>();
        for (Map<String, Object> map : chartsDataList) {
            String name = (String) map.get("name");
            if (StrUtil.isNotBlank(name)) {
                Integer value = (Integer) map.get("value");
                valueList.add(value);
            }
        }
        return valueList;
    }

    private Object getOkCount(String key, List<DataStatisticsEntity> dataStatisticsList) {
        Integer tempKey = Integer.valueOf(StrUtil.removePrefix(key, "okType"));
        for (DataStatisticsEntity dataStatisticsEntity : dataStatisticsList) {
            if (tempKey.equals(dataStatisticsEntity.getOkType())) {
                log.debug("tempKey:{},dataStatisticsEntity:{}", tempKey, dataStatisticsEntity);
                return dataStatisticsEntity.getCount();
            }
        }

        return 0;
    }

    @Override
    public JqGridEntity getStatisticsColNamesAndModel(Integer machineId) {
        //从ok_type表中查询数据
        List<OkTypeEntity> okTypeList = okTypeService.getOkTypeListByMachineId(machineId);

        if (CollUtil.isEmpty(okTypeList)) {
            throw new RuntimeException("请联系管理员配置数据统计参数!");
        }

        List<String> okTypeNameList = okTypeList.stream().map(OkTypeEntity::getDescription).collect(Collectors.toList());
        List<String> colNameList = okTypeNameList;
        log.debug("表头列表:{}", colNameList);

        List<String> errorTypeModelList = okTypeList.stream().map(okTypeEntity -> "okType" + okTypeEntity.getId()).collect(Collectors.toList());
        List<String> colModelList =errorTypeModelList;
        log.debug("模型列表:{}", colModelList);

        List<Integer> sortList = okTypeList.stream().map(OkTypeEntity::getSort).collect(Collectors.toList());

        //根据colModelList拼装colModel
        //{ label: '项目id', name: 'id', index: 'id', width: 50,sortable: false, key: true },
        List<Map<String, Object>> colModelEntity = assembleJqidColModelList(colNameList, colModelList);
        log.debug("colModel实体:{}", colModelEntity);

        MachineEntity machineEntity = machineService.selectById(machineId);
        JqGridEntity jqGridEntity = new JqGridEntity();
        jqGridEntity.setColNameList(colNameList);
        jqGridEntity.setColModelList(colModelList);
        jqGridEntity.setSortList(sortList);
        jqGridEntity.setColModelEntity(colModelEntity);
        jqGridEntity.setMachineEntity(machineEntity);
        jqGridEntity.setOkTypeNameList(okTypeNameList);

        return jqGridEntity;
    }

    private Map<String, Integer> getTime() {
        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();

        boolean begin = true;
        for (int i = 0; i <= 23; i++) {
            for (int j = 0; j < 2; j++) {
                StringBuilder sb = new StringBuilder();
                if (String.valueOf(i).length() == 1) {
                    sb.append("0");
                }
                sb.append(i);
                sb.append(":");
                if (begin) {
                    sb.append("00");
                    begin = false;
                } else {
                    sb.append("30");
                    begin = true;
                }
                map.put(sb.toString(), 0);
            }
        }
        return map;
    }


    //获取检测数据
    private List<Map<String, Object>> getCheckDataList(MachineCheckEntity machineCheck, List<MachineDataEntity> uncheckMachineDataList, ConvertMachineDataEntity convertMachineDataEntity) {
        if (machineCheck.getType() == CheckTypeEnums.FIRST_CHECK.getCode()) {
            return getFirstCheckDataList(machineCheck, uncheckMachineDataList, convertMachineDataEntity);
        }
        if (machineCheck.getType() == CheckTypeEnums.SECOND_CHECK.getCode()) {
            return getSecondCheckDataList(machineCheck, uncheckMachineDataList, convertMachineDataEntity);
        }
        return new ArrayList<>();
    }

    //获取巡检数据
    private List<Map<String, Object>> getSecondCheckDataList(MachineCheckEntity machineCheck, List<MachineDataEntity> uncheckMachineDataList, ConvertMachineDataEntity convertMachineDataEntity) {
        log.debug("开始巡检");
        //如果是巡检则随机取5个
        if (uncheckMachineDataList.size() <= machineCheck.getCount()) {
            log.debug("未检查的数据列表数量小于{},列表size:{}", machineCheck.getCount(), uncheckMachineDataList.size());
            //如果列表数量小于5,则不需要随机取,直接使用即可
            for (MachineDataEntity machineDataEntity : uncheckMachineDataList) {
                machineDataEntity.setChecked(CheckEnums.CHECKED.getCode());
            }
            this.updateBatchById(uncheckMachineDataList);
            return convertMachineDataList(uncheckMachineDataList, convertMachineDataEntity);
        } else {
            //数量大于5,则需要随机取5个
            log.debug("未检查的数据列表数量大于{},列表size:{},开始随机取5个", machineCheck.getCount(), uncheckMachineDataList.size());
            Set<MachineDataEntity> secondCheckDataSet = RandomUtil.randomEleSet(uncheckMachineDataList, 5);
            for (MachineDataEntity machineDataEntity : secondCheckDataSet) {
                machineDataEntity.setChecked(CheckEnums.CHECKED.getCode());
            }
            List<MachineDataEntity> secondCheckDataList = CollUtil.newArrayList(secondCheckDataSet);
            this.updateBatchById(secondCheckDataList);

            //因为是随机取的数据,所有需要根据开始时间排序
            log.debug("排序前:{}", secondCheckDataList);
            secondCheckDataList = CollUtil.sortByProperty(secondCheckDataList, "startTime");
            log.debug("排序后:{}", secondCheckDataList);

            return convertMachineDataList(secondCheckDataList, convertMachineDataEntity);
        }
    }

    //获取首检数据
    private List<Map<String, Object>> getFirstCheckDataList(MachineCheckEntity machineCheck, List<MachineDataEntity> uncheckMachineDataList, ConvertMachineDataEntity convertMachineDataEntity) {
        log.debug("开始首检");
        //如果是首检,则取前5个
        List<MachineDataEntity> firstCheckDataList = CollUtil.sub(uncheckMachineDataList, 0, machineCheck.getCount());
        //如果不为空,则改变这些数据的check为1
        for (MachineDataEntity machineDataEntity : firstCheckDataList) {
            machineDataEntity.setChecked(CheckEnums.CHECKED.getCode());
        }
        this.updateBatchById(firstCheckDataList);
        return convertMachineDataList(firstCheckDataList, convertMachineDataEntity);
    }

    private Boolean checkTimeValid(String endTime) {
        DateTime now = DateUtil.date();
        boolean isValid = now.after(DateUtil.parseDateTime(endTime));
        log.debug("当前时间:{},结束时间:{},是否有效:{}", now, endTime, isValid);
        return isValid;
    }

    //获取检测数据
    private List<MachineDataEntity> getMachineCheckData(Integer machineId, String startTime, String endTime, Integer check) {
        EntityWrapper<MachineDataEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("machine_id", machineId);
        wrapper.ge("start_time", startTime);
        wrapper.le("start_time", endTime);
        wrapper.eq("checked", check);
        wrapper.orderBy("start_time", true);
        return this.selectList(wrapper);
    }

    private HashMap<String, Object> convertMachineData2ColModel(JSONObject machineJson, ConvertMachineDataEntity convertMachineDataEntity) {
        HashMap<String, Object> colModel = new HashMap<>();
        List<String> colModelList = convertMachineDataEntity.getColModelList();
        for (String key : colModelList) {
            Object value = machineJson.get(key); //可能返回null,可能返回"null"
            if (ObjectUtil.isNull(value)) {
                colModel.put(key, Constant.INVALID_DATA);
            } else {
                //格式化
                value = formatDate(key, value);
                value = formatStatus(key, value);
                value = formatErrorType(key, value, convertMachineDataEntity.getErrorTypeMap());

                colModel.put(key, value);
            }
        }
        log.debug("colModel:{}", colModel);
        return colModel;
    }

    private Object formatErrorType(String key, Object value, Map<Integer, String> errorTypeMap) {
        if (key.equals("errorType")) {
            int errorTypeId = (int) value;
            if (errorTypeId == Constant.ERROR_TYPE_SUCCESS) {
                value = Constant.INVALID_DATA;
            } else {
                value = errorTypeMap.get(errorTypeId);
            }
        }
        return value;
    }

    private Object formatStatus(String key, Object value) {
        if (key.equals("status")) {
            if ((int) value == 1) {
                value = "成功";
            } else {
                value = "异常";
            }
        }
        return value;
    }

    private Object formatDate(String key, Object value) {
        if (key.equals("startTime") || key.equals("endTime")) {
            Date date = new Date((Long) value);
            value = DateUtil.formatDateTime(date);
        }
        return value;
    }

    private List<Map<String, Object>> convertMachineDataList(List<MachineDataEntity> machineDataList, ConvertMachineDataEntity convertMachineDataEntity) {
        List<Map<String, Object>> resultList = new ArrayList<>();

        for (MachineDataEntity machineData : machineDataList) {
            JSONObject machineJson = convertMachineData2Json(machineData);
            resultList.add(convertMachineData2ColModel(machineJson, convertMachineDataEntity));
        }

        return resultList;
    }

    private JSONObject convertMachineData2Json(MachineDataEntity machineData) {
        JSONObject machineJson = JSONUtil.parseObj(machineData);
        JSONObject dataJson = JSONUtil.parseObj(machineData.getData());
        machineJson.putAll(dataJson);
        return machineJson;
    }

    private List<Map<String, Object>> assembleJqidColModelList(List<String> colNameList, List<String> colModelList) {
        List<Map<String, Object>> colModelEntity = new ArrayList<>();
        for (int i = 0; i < colNameList.size(); i++) {
            Map<String, Object> colModel = new HashMap<>();
            colModel.put("label", colNameList.get(i));
            colModel.put("name", colModelList.get(i));
            colModel.put("sortable", false);
            colModelEntity.add(colModel);
        }
        return colModelEntity;
    }

    private Integer getErrorCount(String key, List<DataAnalyzeEntity> dataAnalyzeList) {

        Integer tempKey = Integer.valueOf(StrUtil.removePrefix(key, "errorType"));
        for (DataAnalyzeEntity dataAnalyzeEntity : dataAnalyzeList) {
            if (tempKey.equals(dataAnalyzeEntity.getErrorType())) {
                log.debug("tempKey:{},dataAnalyzeEntity:{}", tempKey, dataAnalyzeEntity);
                return dataAnalyzeEntity.getCount();
            }
        }

        return 0;
    }

    private String calculateQualificationRate(Integer qualifiedCount, Integer totalCount) {
        if (totalCount == 0) {
            return Constant.INVALID_DATA;
        }

        log.debug("总数:{},合格数:{}", totalCount, qualifiedCount);

        Double qualificationRate = NumberUtil.div(qualifiedCount, totalCount).doubleValue();
        return NumberUtil.formatPercent(qualificationRate, 2);
    }

    private Integer getTotalCount(List<DataAnalyzeEntity> dataAnalyzeList) {
        Integer totalCount = 0;
        for (DataAnalyzeEntity dataAnalyzeEntity : dataAnalyzeList) {
            totalCount += dataAnalyzeEntity.getCount();
        }
        return totalCount;
    }

    private Integer getDisqualifiedCount(List<DataAnalyzeEntity> dataAnalyzeList) {
        int disqualifiedCount = 0;
        for (DataAnalyzeEntity dataAnalyzeEntity : dataAnalyzeList) {
            if (dataAnalyzeEntity.getErrorType() != Constant.ERROR_TYPE_SUCCESS) {
                disqualifiedCount += dataAnalyzeEntity.getCount();
            }
        }
        return disqualifiedCount;
    }

    private Integer getQualifiedCount(List<DataAnalyzeEntity> dataAnalyzeList) {

        for (DataAnalyzeEntity dataAnalyzeEntity : dataAnalyzeList) {
            if (dataAnalyzeEntity.getErrorType() == Constant.ERROR_TYPE_SUCCESS) {
                return dataAnalyzeEntity.getCount();
            }
        }

        return 0;
    }


}
